package com.shengde.jinwawaforleader.model.myJob.everyRecipe;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.shengde.jinwawaforleader.R;
import com.shengde.jinwawaforleader.network.BaseProtocol;
import com.shengde.jinwawaforleader.utils.UmengShareUtil;
import com.shengde.jinwawaforleader.views.photoview.PhotoView;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

public class PhotoViewZoomActivity extends Activity {
    private static final int DOWNLOAD_OK = 0;
    private static final int SHARE_OK = 1;
    private ArrayList<String> imgData = new ArrayList<>();
    private ViewPager viewpager;
    private int pos = 0;
    Bitmap bitmap = null;
    String content001;
    Dialog dialog;
    private TextView tv_title;
    private TextView tv_back;
    private TextView fill_add;
    private Handler handler = new Handler(){
        public void handleMessage(Message msg){
            switch (msg.what) {
                case  DOWNLOAD_OK:
                    savefile(bitmap);
                    break;
                case SHARE_OK:
                    String url = BaseProtocol.IMG_BASE+ content001;
                    UmengShareUtil.share(PhotoViewZoomActivity.this,"菜谱图片分享",url,url,url);
                    break;
            }
        }
    };
    @SuppressWarnings("unchecked")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_photo_view_zoom);
        tv_title = (TextView)findViewById(R.id.tv_title);
        tv_back = (TextView)findViewById(R.id.tv_back);
        fill_add = (TextView)findViewById(R.id.fill_add);
        tv_title.setText("照片");
        fill_add.setVisibility(View.INVISIBLE);
        if (Build.VERSION.SDK_INT >= 11) {
            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                    .detectDiskReads().detectDiskWrites().detectAll()
                    .penaltyLog().build());
            StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                    .detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
                    .penaltyLog().build());
        }
        Intent mIntent = getIntent();
        pos = mIntent.getIntExtra("position", 0);
        imgData=mIntent.getStringArrayListExtra("imgData");
        content001 = imgData.get(0);
        viewpager = (ViewPager) findViewById(R.id.viewpager);
        viewpager.setAdapter(new SamplePagerAdapter(imgData));
        viewpager.setCurrentItem(pos);

        listener();
    }

    private void listener() {
        //退出当前界面
        tv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        viewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                // TODO Auto-generated method stub
                content001=	imgData.get(arg0);

            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                // TODO Auto-generated method stub

            }
        });
    }


    class SamplePagerAdapter extends PagerAdapter {
        private ArrayList<String> list;

        public SamplePagerAdapter(ArrayList<String> alist) {
            this.list = alist;
        }
        @Override
        public int getCount() {
            return list.size();
        }
        @Override
        public View instantiateItem(ViewGroup container, int position) {
            PhotoView photoView = new PhotoView(container.getContext());
            String c = list.get(position);
            Glide.with(PhotoViewZoomActivity.this).load(BaseProtocol.IMG_BASE+c).error(R.drawable.food).into(photoView);
            System.out.println("罗明"+BaseProtocol.IMG_BASE+c);
            photoView.setScaleType(ImageView.ScaleType.FIT_CENTER);
            photoView.setBackgroundColor(0);
            container.addView(photoView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            photoView.setOnLongClickListener(new View.OnLongClickListener() {

                @Override
                public boolean onLongClick(View v) {
                    // TODO Auto-generated method stub
                    chakan();
                    return true;
                }
            });

            return photoView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
            position=-2;
        }
        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

    }
    protected void savefile(Bitmap bitmap) {
        // TODO Auto-generated method stub
        File dirfile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/金娃娃教师版/");
        if (!dirfile.exists()) {
            dirfile.mkdir();
        }
        File filename = new File(dirfile , System.currentTimeMillis()+".png");
        if (filename.exists()) {
            filename.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(filename);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            out.flush();
            out.close();
            Toast toast = Toast.makeText(getApplicationContext(), "保存成功",
                    Toast.LENGTH_SHORT);
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(filename);
            intent.setData(uri);
            PhotoViewZoomActivity.this.sendBroadcast(intent);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    private Bitmap returnBitmap(int flag , String url) {
        // TODO Auto-generated method stub

        InputStream is = null;
        HttpURLConnection con = null;
        try {
            // 建立网络连接
            URL imageURl = new URL(url);
            con = (HttpURLConnection) imageURl.openConnection();
            con.connect();
            is = con.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            con.disconnect();
        }
        if (bitmap == null) {
            bitmap = BitmapFactory.decodeResource(getApplicationContext()
                    .getResources(), R.drawable.touxiang);
        }
        handler.sendEmptyMessage(flag);
        return bitmap;
    }
    protected void chakan() {
        // TODO Auto-generated method stub
        System.out.println("AlbumImageBrowserActivityc.cc()");
        dialog = new Dialog(PhotoViewZoomActivity.this, R.style.dialog);
        View contentView = LayoutInflater.from(PhotoViewZoomActivity.this).inflate(
                R.layout.tupian_content, null);//
        dialog.setContentView(contentView);
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
        TextView textView1 = (TextView) contentView.findViewById(R.id.textView1);
        TextView textView2 = (TextView) contentView.findViewById(R.id.textView2);
        TextView textView3 = (TextView) contentView.findViewById(R.id.textView3);
        System.out.println("AlbumImageBrowserActivityc.cc()");
        //本地
        textView1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                Toast.makeText(PhotoViewZoomActivity.this, "图片保存中,请稍候", Toast.LENGTH_SHORT).show();
                String url = BaseProtocol.IMG_BASE+ content001;
                if (url.endsWith("null")) {
                    Toast.makeText(PhotoViewZoomActivity.this, "图片保存失败", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    new Thread(){
                        public void run(){
                            returnBitmap(DOWNLOAD_OK,BaseProtocol.IMG_BASE+ content001);
                        }
                    }.start();
                }
            }
        });
        //分享
        textView2.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                dialog.dismiss();
                Toast.makeText(PhotoViewZoomActivity.this, "图片分享处理中,请稍候", Toast.LENGTH_SHORT).show();
                final String url = BaseProtocol.IMG_BASE+ content001;
                if (url.endsWith("null")) {
                    Toast.makeText(PhotoViewZoomActivity.this, "图片分享失败", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    new Thread(){
                        public void run(){
                            returnBitmap(SHARE_OK,url);
                        }
                    }.start();
                }
            }
        });
        //取消
        textView3.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }
}